import { logger } from '@vscode/debugadapter';
import { AxiosError } from 'axios';
import { window } from 'vscode';

/**
 * 生成 uuid
 *
 * @author chitanda
 * @date 2022-11-30 10:11:25
 * @export
 * @return {*}  {string}
 */
export function uuid(): string {
  // eslint-disable-next-line @typescript-eslint/naming-convention
  function S4() {
    // eslint-disable-next-line no-bitwise
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return `${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}
/**
 * 获取随机字符串
 *
 * @author chitanda
 * @date 2021-11-15 18:11:11
 * @export
 * @return {*}  {string}
 */
export function getNonce(): string {
  let text = '';
  const possible =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < 32; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

/**
 * 显示错误信息
 *
 * @author chitanda
 * @date 2022-12-13 10:12:50
 * @export
 * @param {unknown} error
 */
export function showErrInfo(error: unknown): void {
  if (error instanceof AxiosError) {
    const { response } = error;
    let msg = '未知异常';
    if (response) {
      const { data } = response;
      if (data) {
        if (data.message) {
          msg = data.message;
        } else {
          msg = `${response.status}: ${data.error}`;
        }
      }
    }
    window.showErrorMessage(msg);
  }
  if (error instanceof Error) {
    logger.error(error.message);
  }
}
